package com.mystnihon.freeremote.ui.fragment;

import java.util.Observable;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.mystnihon.freeremote.R;
import com.mystnihon.freeremote.db.DBHelper;
import com.mystnihon.freeremote.db.DBHelper.ChanProg;
import com.mystnihon.freeremote.manager.GuideNetworkManager;
import com.mystnihon.freeremote.util.Constants;
import com.mystnihon.widget.ListItemButton;
import com.novoda.imageloader.core.ImageManager;
import com.novoda.imageloader.core.model.ImageTagFactory;

public class ChannelsListFragment extends DefaultObserverSherlockFragment implements LoaderCallbacks<Cursor> {

	private static final int CHANNELS = 0;

	private GuideNetworkManager mGuideManager;
	private ChannelAdapter mChannelAdapter;
	private ListView mListView;
	private ImageTagFactory mImageTagFactory;
	private ImageManager mImageManager;

	@Override
	public void update(Observable observable, Object data) {
		if (observable instanceof GuideNetworkManager) {
			getLoaderManager().restartLoader(CHANNELS, null, this);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.fragment_channel_list, container, false);
		mListView = (ListView) v.findViewById(R.id.fr_channel_listview);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		registerManager();
		initView();
		initCursorLoader();
		mGuideManager.getChannelForNow();

	}

	private void initView() {
		mImageTagFactory = ImageTagFactory.newInstance(60, 60, -1);
		mChannelAdapter = new ChannelAdapter(getActivity(), null, ChannelAdapter.NO_SELECTION);
		mListView.setAdapter(mChannelAdapter);
		mListView.setOnItemClickListener(mChannelAdapter);

	}

	private void initCursorLoader() {
		getLoaderManager().initLoader(CHANNELS, null, this);

	}

	private void registerManager() {
		mImageManager = getMyApplication().getImageManager();
		mGuideManager = getMyApplication().getGuideManager();
		putObservable(mGuideManager);

	}

	public class ChannelAdapter extends CursorAdapter implements OnItemClickListener {
		// private static final String HOUR_FORMAT = "HH'H'mm";
		// private SimpleDateFormat mDateFormat;
		private LayoutInflater mInflater;

		class ViewHolder {
			ImageView mChannel;
			TextView mTitle;
			// TextView mTime;
			TextView mDescription;
			ListItemButton mButton;
			// TextView mNextProg;
			// LinearLayout mDescriptionZone;
			// RelativeLayout mContainer;
			// ProgressBar mProgressBar;
		}

		public ChannelAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			// mDateFormat = new SimpleDateFormat(HOUR_FORMAT,
			// Locale.getDefault());
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewHolder viewHolder = (ViewHolder) view.getTag();
			final ChanProg channel = ChanProg.inflateObject(cursor);
			setData(context, view, viewHolder, channel);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			final ViewHolder viewHolder = new ViewHolder();
			final View convertView = mInflater.inflate(R.layout.listitem_channel, null);
			viewHolder.mChannel = (ImageView) convertView.findViewById(R.id.fr_listitem_channel_logo);
			viewHolder.mTitle = (TextView) convertView.findViewById(R.id.fr_listitem_program_name);
			viewHolder.mDescription = (TextView) convertView.findViewById(R.id.fr_listitem_program_description);
//			viewHolder.mButton = (ListItemButton) convertView.findViewById(R.id.fr_listitem_button_zap);
//			viewHolder.mButton.setOnClickListener(mZapListener);

			convertView.setTag(viewHolder);

			final ChanProg channel = ChanProg.inflateObject(cursor);

			setData(context, convertView, viewHolder, channel);

			return convertView;
		}

		private void setData(Context context, View convertView, ViewHolder viewHolder, ChanProg progForChan) {
			viewHolder.mTitle.setText(progForChan.mProgTitle);
			viewHolder.mChannel.setContentDescription(progForChan.mChannelName);
			viewHolder.mDescription.setText(progForChan.mDescription);
			downloadImage(viewHolder.mChannel, Constants.IMAGE_CHAINE + progForChan.mImage, context);

		}

		private void downloadImage(ImageView view, String url, Context context) {
			view.setTag(mImageTagFactory.build(url, context));
			mImageManager.getLoader().load(view);
		}

		@Override
		public ChanProg getItem(int position) {
			final Cursor cursor = getCursor();
			final int prevPos = cursor.getPosition();
			cursor.moveToPosition(position);
			final ChanProg lChanProg = ChanProg.inflateObject(cursor);
			cursor.moveToPosition(prevPos);
			return lChanProg;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
			String channelNumber = String.valueOf(getItem(position).mChannelNumber);
			for (int i = 0; i < channelNumber.length(); i++) {
				getMyApplication().getRemote().keyNumber(Character.getNumericValue(channelNumber.charAt(i)));
			}
		}

//		private OnClickListener mZapListener = new OnClickListener() {
//
//			@Override
//			public void onClick(View view) {
//				int position = mListView.getPositionForView(view);
//				if (position != ListView.INVALID_POSITION) {
//					String channelNumber = String.valueOf(getItem(position).mChannelNumber);
//					System.out.println("channel number " + channelNumber);
//					for (int i = 0; i < channelNumber.length(); i++) {
//						getMyApplication().getRemote().keyNumber(Character.getNumericValue(channelNumber.charAt(i)));
//					}
//				}
//
//			}
//		};
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case CHANNELS:
				return DBHelper.getCurrentProgramsChannelCursorLoader(getSherlockActivity(), System.currentTimeMillis());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor newCursor) {
		switch (loader.getId()) {
			case CHANNELS:
				mChannelAdapter.swapCursor(newCursor);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		switch (loader.getId()) {
			case CHANNELS:
				mChannelAdapter.swapCursor(null);
		}
	}

}
